<template>
  <div class="app-container">
    <el-form ref="listFilterRef" :model="list.filter" inline>
      <el-form-item prop="categoryIds">
        <CategorySelect
          v-model="list.filter.categoryIds"
          :props="{ multiple: true }"
          placeholder="商品分类"
        />
      </el-form-item>
      <el-form-item prop="name">
        <el-input
          v-model="list.filter.name"
          placeholder="请输入商品名称"
          clearable
        />
      </el-form-item>
      <el-form-item prop="mchId">
        <merchantSelect v-model="list.filter.mchId" noPermission />
      </el-form-item>
      <el-form-item prop="subMchId">
        <SubMchSelect v-model="list.filter.subMchId" noPermission />
      </el-form-item>
      <el-form-item prop="mchAreaCodes">
        <AllRegionSelect
          v-model="list.filter.mchAreaCodes"
          :props="{
            multiple: true
          }"
          :show-all-levels="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-operation">
      <span></span>
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column align="center" type="index" />
      <el-table-column label="图片" prop="productId">
        <template slot-scope="{ row }">
          <PicViewer :value="row.productImg" tableCell />
        </template>
      </el-table-column>
      <!-- <el-table-column label="商品编码" prop="productCode" /> -->
      <el-table-column label="商品类型" prop="categoryName" />
      <el-table-column label="商品名称" prop="productName" />
      <el-table-column label="商户名称" prop="merchantName" />
      <el-table-column label="店铺名称" prop="subMchName" />
      <el-table-column label="商品基础售价（元）">
        <template slot-scope="{ row }">
          {{ row.currentPrice | $cent2yuan }}
        </template>
      </el-table-column>
      <el-table-column label="分销奖励金比例" prop="distributionProportion">
        <template slot-scope="{ row }">
          {{ row.distributionProportion }}%
        </template>
      </el-table-column>
      <el-table-column prop="distributionAmount" width="200">
        <template slot="header">
          预计分销奖励金（元）
          <el-popover placement="bottom" width="320" title="注释说明">
            <p>1、预计分销奖励金=商品单价*（1-0.6%）*分销奖励金比例</p>
            <p>
              2、当前预计分销奖励金是基于当前售价与分销奖励金比例计算，实际奖励金采用实时状态的数据计算，当前预估金额仅供参考
            </p>
            <i
              class="el-icon-question"
              slot="reference"
              style="color: #409eff; cursor: pointer"
            ></i>
          </el-popover>
        </template>
        <template slot-scope="{ row }">
          {{ row.distributionAmount | $cent2yuan }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" prop="createTime" />
      <el-table-column label="状态" prop="status">
        <template slot-scope="{ row }">
          <Tag
            :value="row.status"
            :options="[
              { value: 0, text: '启用', type: 'success' },
              { value: 1, text: '停用', type: 'danger' }
            ]"
          />
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{ row }">
          <AuthButton
            @click="
              () => {
                commodityDetail.id = row.productId
                commodityDetail.businessTypeId = row.businessTypeId
                commodityDetail.show = true
              }
            "
            name="查看"
          />
          <!-- 不可以采购自己店铺的商品 -->
          <AuthButton
            v-if="userInfo.roleId != '-1' && userInfo.merchantId != row.mchId"
            @click="purchase(row)"
            circle
            name="采购"
          />
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="showDialog"
      title="采购商品"
      v-model="purchaseMap"
      :submit="submit"
      ref="formRef"
    >
      <template #el-form>
        <el-form-item label="商品名称">
          {{ purchaseMap.productName__ }}
        </el-form-item>
        <el-form-item label="商品价格">
          {{ purchaseMap.currentPrice__ | $cent2yuan }}元
        </el-form-item>
        <el-form-item label="分销奖励金">
          {{ purchaseMap.distributionProportion__ }}%
          <form-item-tip value="销售商品并完成订单后获得分销奖励金" />
        </el-form-item>
        <el-form-item label="选择要上架的店铺" prop="subMchId" verify>
          <!-- @change="subMchChange" 已经换为使用商品所属方和商品销售方代替 -->
          <KiSelect
            v-model="purchaseMap.subMchId"
            :options="merchantList"
            :props="{ value: 'subMchId', label: 'name' }"
          />
          <form-item-tip value="选择本商户的一个店铺进行销售" />
        </el-form-item>
        <!-- <el-form-item v-if="purchaseMap.subMchId" label="客服提供方" prop="customerMchId" verify>
          <KiSelect v-model="purchaseMap.customerMchId" :options="waiter" optionKey="subMchId/name" />
          <form-item-tip value="可选择商品联系电话和地址显示提供方店铺还是采购方店铺" />
        </el-form-item> -->
        <el-form-item label="客服提供方" prop="customerType" verify>
          <KiSelect
            v-model="purchaseMap.customerType"
            :options="[
              { dataName: '商品所属商户', dataValue: 0 },
              { dataName: '商品销售方', dataValue: 1 }
            ]"
          />
          <form-item-tip value="选择商品所属方或商品销售方" />
        </el-form-item>
        <el-form-item label="热门推荐" prop="recommend" verify>
          <el-switch
            v-model="purchaseMap.recommend"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
          <form-item-tip value="开启后在我的店铺中成为热门推荐的商品" />
        </el-form-item>
      </template>
    </KiFormDialog>

    <CommodityDetail
      v-if="commodityDetail.show"
      :show.sync="commodityDetail.show"
      :id.sync="commodityDetail.id"
      :businessTypeId.sync="commodityDetail.businessTypeId"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import SubMchSelect from '@/components/SubMchSelect'
import merchantSelect from '@/components/merchantSelect'
import CategorySelect from '@/components/CategorySelect'
import CommodityDetail from '@/views/merchant/commodity/form/CommodityDetail.vue'

export default {
  mixins: [pageMixin],
  computed: {
    ...mapGetters(['userInfo'])
  },
  components: {
    SubMchSelect,
    merchantSelect,
    CategorySelect,
    CommodityDetail
  },
  setup: () =>
    useAdmateAdapter({
      urlPrefix: '/sot-admin-api/product/cloud-store',
      list: {
        filter: {
          name: '',
          categoryIds: [],
          mchAreaCodes: [],
          startTime: null,
          endTime: null
        }
      }
    }),
  data () {
    return {
      visible: false,
      showDialog: false,
      purchaseMap: {
        mchId: '',
        productId: '',
        customerMchId: '',
        recommend: 0,
        subMchId: '',
        status: 1
      },
      merchantList: [],
      waiter: [],
      commodityDetail: {
        show: false,
        id: undefined,
        businessTypeId: undefined
      }
    }
  },
  created () {
    // 获取子商铺
    this.$POST('sot-admin-api/merchant/sub/queryListForMch', {
      merchantId: this.userInfo.merchantId,
      status: 1
    }).then(res => {
      this.merchantList = res.data || []
    })
  },
  methods: {
    subMchChange (e) {
      this.merchantList.map(item => {
        if (item.subMchId == e) {
          this.waiter.length = 2
          this.waiter[1] = {
            subMchId: item.subMchId,
            name: item.name
          }
        }
      })
      this.purchaseMap.customerMchId = ''
    },
    purchase (row) {
      if (row.alreadyPurchase == 1) {
        this.$swal.error('该商品已被当前商户采购，无法再次采购。')
        return
      }
      this.purchaseMap = {
        mchId: this.userInfo.merchantId,
        productId: row.productId,
        customerMchId: '',
        recommend: 0,
        subMchId: '',
        status: 1, //默认采购就是上架状态
        productName__: row.productName,
        currentPrice__: row.currentPrice,
        distributionProportion__: row.distributionProportion
      }

      this.waiter = [
        {
          subMchId: row.subMchId,
          name: row.subMchName
        }
      ] // 拼装客服提供方

      if (this.$refs.purchaseForm) {
        this.$refs.purchaseForm.clearValidate()
      }
      this.showDialog = true
    },
    submit () {
      return this.$POST(
        '/sot-admin-api/product/cloud-store/purchaseProduct',
        this.purchaseMap
      ).then(res => {
        if (res.errorCode == '00000') {
          this.$swal.success('采购成功！')
          this.showDialog = false
        } else {
          this.$swal.error(res.message)
        }
      })
    }
  }
}
</script>
